package org.zxyj.core.net.coobird.thumbnailator.filters;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.zxyj.core.net.coobird.thumbnailator.util.BufferedImages;

/**
 * An {@link ImageFilter} which will apply multiple {@link ImageFilter}s in a
 * specific order.
 * 
 * @author coobird
 *
 */
public class Pipeline implements ImageFilter
{
	private List<ImageFilter> filtersToApply;
	private final List<ImageFilter> unmodifiableFiltersToApply;
	public Pipeline()
	{
		this(Collections.<ImageFilter>emptyList());
	}
	
	public Pipeline(ImageFilter... filters)
	{
		this(Arrays.asList(filters));
	}
	
	public Pipeline(List<ImageFilter> filters)
	{
		if (filters == null)
		{
			throw new NullPointerException("Cannot instantiate with a null" + "list of image filters.");
		}
		
		filtersToApply = new ArrayList<ImageFilter>(filters);
		unmodifiableFiltersToApply = Collections.unmodifiableList(filtersToApply);
	}
	
	public void add(ImageFilter filter)
	{
		if (filter == null)
		{
			throw new NullPointerException("An image filter must not be null.");
		}
		filtersToApply.add(filter);
	}

	public void addFirst(ImageFilter filter)
	{
		if (filter == null)
		{
			throw new NullPointerException("An image filter must not be null.");
		}
		filtersToApply.add(0, filter);
	}

	public void addAll(List<ImageFilter> filters)
	{
		if (filters == null)
		{
			throw new NullPointerException("A list of image filters must not be null.");
		}
		filtersToApply.addAll(filters);
	}
	
	public List<ImageFilter> getFilters()
	{
		return unmodifiableFiltersToApply;
	}
	
	public BufferedImage apply(BufferedImage img)
	{
		if (filtersToApply.isEmpty())
		{
			return img;
		}
		BufferedImage image = BufferedImages.copy(img);
		for (ImageFilter filter : filtersToApply)
		{
			image = filter.apply(image);
		}
		return image;
	}
}
